package com.shawn.spring.boot.mybatis.run;

import com.shawn.spring.boot.mybatis.constants.MenuTypeEnum;
import com.shawn.spring.boot.mybatis.entity.Menu;
import com.shawn.spring.boot.mybatis.service.MenuService;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @author shawn
 * @since 2020/8/30
 */
@Component
@Slf4j
public class MybatisRunner implements ApplicationRunner {

  @Autowired private MenuService service;

  @Override
  public void run(ApplicationArguments args) throws Exception {
    log.info("test insert");
    testInsert();
    log.info("test update");
    testUpdate();
    log.info("test find all");
    testFindAll();
    log.info("test find by id");
    testFindById();
    log.info("test delete");
    testDelete();
    log.info("test find by id");
    testFindById();
  }

  private void testInsert() {
    Menu menu =
        Menu.builder()
            .parentId(0)
            .name("test")
            .level(1)
            .type(MenuTypeEnum.CATALOG_TYPE)
            .url("/test")
            .order(1)
            .build();
    service.insert(menu);
  }

  private void testUpdate() {
    Menu newMenu =
        Menu.builder()
            .menuId(1)
            .name("test2")
            .level(2)
            .type(MenuTypeEnum.CATALOG_TYPE)
            .url("/test2")
            .order(2)
            .build();
    service.update(newMenu);
  }

  private void testDelete() {
    service.delete(1);
  }

  private void testFindAll() {
    service.findAll().forEach(menu -> log.info(menu.toString()));
  }

  private void testFindById() {
    Menu menu = service.findById(3);
    if (menu == null) {
      log.warn("not found, id: {}", 3);
    } else {
      log.info(menu.toString());
    }
  }
}
